import axios from 'axios'
import {
  MessageBox,
  Message,
} from 'element-ui'
import {
  showLoading,
  hideLoading
} from '@/utils/loading';
import {
  getToken,
  getShopToken,
  getLoginType,
  logintype_byurl
} from '@/utils/auth'
import mallrouter from '@/applications/mall/router'
import shoprouter from '@/applications/shop/router'
import mallstore from '@/applications/mall/store'
import shopstore from '@/applications/shop/store'

function getstore(n) {
  let type = logintype_byurl();
 if (type == 'mall') {
    var router = mallrouter
    var store = mallstore
  } else if (type == 'shop') {
    var router = shoprouter
    var store = shopstore
  }
  if (n) {
    return store
  } else {
    return router
  }
}
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 300000, // request timeout
  // headers:{
  //   'Content-Type':'application/x-www-form-urlencoded'
  // }
})
var n_load = 0
// request interceptor
service.interceptors.request.use(config => {
  // do something before request is sent
  //匹配url中是否包含shop字段
  let pat = /shop/;
  let madmin = /madmin/
  let integralshop = /integral\/shop/
  //匹配url中是否包含login字段
  let lg = /login/;
  let wxlg = /wxa\/config\/login/;
  let myconfig = /configuration\//
  var numreg = /[\s\S]*\d$/g;
  // let each request carry token
  // ['Authorization'] is a custom headers key
  // please modify it according to the actual situation
  if (pat.test(config.url) && !integralshop.test(config.url) && getLoginType() == 'mall') {
    config.headers['Authorization'] = getShopToken();
  } else {
    config.headers['Authorization'] = getToken();
  };
  if (lg.test(config.url) && !wxlg.test(config.url)) {
    if (config.data.merchant_id || config.data.mall_id) {
      config.headers['Authorization'] = getToken();
    } else {
      config.headers['Authorization'] = '';
    }
  };
  let type = logintype_byurl();
  if (type == 'saas') {
    var router = saasrouter
    var store = saasstore
  } else if (type == 'mall') {
    var router = mallrouter
    var store = mallstore;
    config.headers['Affiliation'] = type
  } else if (type == 'shop') {
    var router = shoprouter
    var store = shopstore
    config.headers['Affiliation'] = type
  }
  if (type != 'user' && (!lg.test(config.url) || wxlg.test(config.url)) && router.currentRoute && router
    .currentRoute.meta.id && store.state.user.ruleList) {
    let id = router.currentRoute.meta.id;
    let ruleList = store.state.user.ruleList
    let l = ruleList.filter(_ => {
      return _.level == id
    })
    let PageAction = ''
    let url = config.url
    if (url.indexOf("?") > -1) {
      url = url.substr(0, url.indexOf("?"))
    }
    if (myconfig.test(url) && !madmin.test(url)) {
      url = url.substr(0, url.indexOf("configuration") + 14) + '<type>';
    }
    if (numreg.test(url)) {
      url = url.replace(/[\d]+/, '<id>')
    }
    if (l.length > 0) {
      l.forEach(_ => {
        let i = _.ruleExtend.findIndex(a => {
          return config.method == a.method.toLowerCase() && url == a.rule_route
        })

        if (i > -1) {
          PageAction = _.level + ',' + _.resource
        }
      })
    }
    config.headers['PageAction'] = PageAction
  }
  if (config.data && config.data.n_load == 1) {
    n_load = 1
    delete config.data.n_load
  } else {
    n_load = 0
    showLoading()
    // // this.isLoading=true;
  }
  return config
}, error => {
  // do something with request error
  console.log(error) // for debug
  return Promise.reject(error)
})
// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */
  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    hideLoading();
    const res = response
    let store = getstore(1)
    let router = getstore(0)
    // Loading.close();
    // if the custom code is not 20000, it is judged as an error.
    if (res.status == 200) {
      return res.data
    } else if (res.status == 201) {
      Message({
        message: "操作成功",
        type: 'success',
        duration: 2 * 1000
      })
      return res.data
    } else if (res.status == 203) {
      store.dispatch('user/setlicense')
    } else if (res.status == 204) {
      Message({
        message: "删除成功",
        type: 'success',
        duration: 2 * 1000
      })
      return true
    } else if (res.status == 401) {
      Message({
        message: "请登录",
        type: 'error',
        duration: 2 * 1000
      })
      store.dispatch('user/logout')
      router.push('/login')
    } else if (res.status == 403) {} else {
      Message({
        message: res.data.msg || res.data.error_msg || '系统错误',
        type: 'error',
        duration: 2 * 1000
      })
      return Promise.reject(new Error(res.data.msg || 'Error'))
    }
  }, error => {
    hideLoading();
    let store = getstore(1)
    let router = getstore(0)
    if (error.response.status == 401) {
      Message({
        message: "请登录",
        type: 'error',
        duration: 2 * 1000
      })
      store.dispatch('user/logout')
      router.push('/login')
    } else if (error.response.status == 403) {
      let type = logintype_byurl();
      // window.location.href = type + '.html'
      // location.reload()
    } else if (error.response.status == 203) {
      store.dispatch('user/setlicense')
    } else {

        Message({
          message: error.response.data.error_msg || error.response.data.msg,
          type: 'error',
          duration: 2 * 1000
        })
      
      return Promise.reject(error)
    }
  })
export default service
